package com.ht.WeNas.dao.repo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ht.WeNas.config.data.CacheNameEnum;
import com.ht.WeNas.dao.mapper.UserMapper;
import com.ht.WeNas.data.dto.UserDto;
import com.ht.WeNas.data.entity.User;
import com.ht.WeNas.utils.CacheUtil;
import org.springframework.stereotype.Repository;

@Repository
public class UserRepo {
    private final CacheUtil cacheUtil;
    private final UserMapper thisMapper;

    public UserRepo(CacheUtil cacheUtil, UserMapper thisMapper) {
        this.cacheUtil = cacheUtil;
        this.thisMapper = thisMapper;
    }
    
    public User getUserById(long id) {
        return cacheUtil.cacheRead(CacheNameEnum.User_By_Id, id, thisMapper::selectById);
    }

    public User getUserByName(String username) {
        return cacheUtil.cacheRead(
                CacheNameEnum.User_By_Name,
                username,
                (key) -> thisMapper.selectOne(
                        Wrappers.lambdaQuery(User.class)
                                .eq(User::getUsername, key)
                                .last("limit 1")
                )
        );
    }

    public void deleteUser(long id) {
        Object o = cacheUtil.cacheRead(CacheNameEnum.User_By_Id, id);
        if (o instanceof UserDto) {
            cacheUtil.dropCache(CacheNameEnum.User_By_Name, ((UserDto) o).getUsername());
        }
        cacheUtil.dropCache(CacheNameEnum.User_By_Id, id);
        thisMapper.deleteById(id);
    }
    
    public void updateById(User user) {
        cacheUtil.dropCache(CacheNameEnum.User_By_Name, user.getUsername());
        cacheUtil.dropCache(CacheNameEnum.User_By_Id, user.getId());
        thisMapper.updateById(user);
    }

    public void save(User user) {
        this.thisMapper.insert(user);
    }

    public boolean exists(LambdaQueryWrapper<User> eq) {
        return this.thisMapper.exists(eq);
    }
}
